Repository navigation
Conversation
…still works A token is refreshed only when a call asks for one within 90 seconds of its expiry, and that call waits for the refresh. After a failure, every later call starts another at once. These tests pin what #1962 asks for: - a caller with a valid token gets it at once, in stack-auth and in Go; - a token in use is refreshed ahead of its expiry with no caller asking, and an idle strategy stops refreshing; - after a refresh fails, callers with an expired token fail fast with its error rather than each starting an exchange, and the refresh is retried with growing gaps; - dropping a strategy leaves nothing running. They fail on the current code. Refs #1962
…nd, with backoff Nothing refreshed a token before a call needed one. The first call in the last 90 seconds refreshed and waited, and after a failure every later call started another exchange at once. The rule now lives once, in RefreshSchedule. It reads no clock and starts no task, so every host can drive it: - a token's refresh is due 90 to 120 seconds before expiry, with jitter, or half way through its life if that is later; - only while the strategy is in use: each call marks it, and each attempt clears the mark, so an idle process stops asking; - after a failure the next attempt waits about a second, doubling up to 30 seconds, and a minute after a refusal of the account. A clock read before the failure ends the backoff, as it ends a cached refusal. The refresh engine keeps the plan. Natively it starts one Tokio task per strategy on the first get_token. The task holds the strategy weakly and ends when it is dropped. While a driver is attached, a call with a token that still works never starts or waits for a refresh. In every mode, a call whose token has expired fails at once with the failed refresh's error until the backoff ends. A server fault keeps its kind there, so a caller that retries on one still does. A host with no task (a WebAssembly host) drives the same rule through AccessKeyStrategy and DeviceSessionStrategy: drive_refresh holds a RefreshDriver, and next_refresh and refresh_now are the timer's two calls. Tests of the in-window paths that wasm32 still runs build their engine call_driven. The cancellation soak runs each seed both ways. Refs #1962
…outine stack-auth's rule now decides when a token is refreshed ahead of its expiry, and the guest keeps it. A WebAssembly guest has no background task, so the Go host keeps the timer. - Two new step operations: sa_auth_next_refresh says when the next refresh is due (or idle until the token is used again), and sa_auth_refresh_ahead refreshes if it still is. - A strategy created with refresh_ahead leaves refreshing a token that still works to the host. Go sets it for access keys and device sessions. The guest holds stack-auth's RefreshDriver for an access key. For a device session it keeps a RefreshSchedule (the plan only, never the token) and replays the last refresh error while the refresh backs off. - auth.Strategy runs one loop goroutine for each such strategy. It starts idle, wakes on a successful Token, and sleeps until the refresh is due. It refreshes through the step loop, so it never holds the profile's lock while it sleeps. A device session refreshes as Token does, one at a time in the process and under the cross-process lock. - The loop holds the strategy through a weak.Pointer. Strategy.Close stops it and waits for it, ProfileStore.Close ends it, and a strategy the application never closes is still collected, its cleanup ending the loop. An OIDC strategy has no loop: its provider is asked for a JWT on every call, which a timer cannot do. The two tests in which a caller started the refresh of a token that still works now have the background refresh in flight instead. Refs #1962
…ry mutant cargo-mutants found behaviour of the new rule and the background task that no test pinned. Tests now pin each of these: - the host-driver calls, next_refresh, refresh_now and drive_refresh, on both strategies; - a task ending with its runtime, and a strategy's drop waking its task; - a refresh made before the task wakes not being repeated; - the half-way rule, the whole jitter window, the whole range of each backoff wait, and SplitMix64's known answers. The task's loop is simpler. It always waits until the refresh it read is due, then attempts it, then waits at least a second. Before, a plan that stayed due could make the task spin without yielding. refresh_now with no token yet now makes the first exchange, for a strategy that can. The cancellation tests bound each gate's wait, so a refresh that never starts fails the test instead of hanging it. Refs #1962
Under the race detector opening the profile can take longer than the test token's four seconds, so the first Token found it expired and refreshed it inline. Refs #1962
🦋 Changeset detectedLatest commit: 2c14afe The changes in this PR will be included in the next version bump. This PR includes changesets to release 19 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the
|
drivers_attached and call_driven are used only by test modules that build with the http feature. Without it (the wasm:no-http-test shape the WASI guest builds against) they were dead code, and -D warnings failed the build.
Mutation testing (cargo-mutants,
|
| caught | missed | unviable | timeout |
|---|---|---|---|
| 41 | 0 | 30 | 0 |
cargo-mutants exited with no surviving mutants recorded. The run may not have completed cleanly; check the workflow run logs.
The mutants gate timed out on two mutants of the driver check in get_token (`attached > 0` to `>= 0` or `== 0`). Under either, a strategy with no driver believes one is attached, so no caller starts the refresh, and the tests waiting for it to begin hung until the gate gave up. A timeout counts as a surviving mutant. Add a test that a caller starts the refresh when nothing drives it, and bound every wait for a refresh to start at 5 seconds, so both mutants now fail within seconds.
… task Each per-JWT engine of an OidcFederationStrategy started its own background task on first use, so a server would keep re-exchanging a user's JWT ahead of expiry for as long as that user stayed active, one task per cached user. That is more calls to CTS than the old behaviour, and a re-exchange late in a session can fail once the JWT itself has expired. OIDC engines are now built refreshed_by_calls: no task, and a call in the last 90 seconds refreshes as before. Access-key and device-session strategies, where one process owns the credential, keep their task. The Go guest already treated OIDC as idle. Refs #1962
cipherstash-agent
left a comment
There was a problem hiding this comment.
Review attestation
Reviewed 65fa82be · posted from Claude Code (scheduled routine) · claude-opus-5-5 · effort medium
Sources: code-review · claude-opus-5-5; rust-security agent · claude-opus-5-5; code-review standards and spec agents · claude-opus-5-5; review-cross-check verification agents · claude-opus-5-5
Skills: code-review, company-skills:rust-security, mattpocock-skills:code-review, company-skills:review-cross-check, company-skills:review-post
Findings (7): 4 major, 3 minor — 7 inline, 0 below.
Initial reviews read 1f1fb777; every finding was re-verified against 65fa82be. The background OIDC refresh concern is fixed by 65fa82be and dropped.
Generated by Claude Code
| // than every call making an exchange of its own. | ||
| let usable = state.token.as_ref().is_some_and(|t| t.is_usable_at(now)); | ||
| let driven = self.driver.attached.load(Ordering::Acquire) > 0; | ||
| if usable && (driven || state.schedule.backing_off(now)) { |
There was a problem hiding this comment.
major After a quiet period the plan is idle (attempt_started cleared used), so a call inside the 90 s leeway only wakes the driver and still gets the cached token here, e.g. with 2 s left (reproduced with a paused clock: issued-1 with 2s left, calls=1). Before this PR that call refreshed and got a fresh token, which refresh_non_blocking's comment exists to guarantee. Skip the inline refresh only when the driver was already scheduled before this call (schedule.used() returned false) or the token is outside the leeway; otherwise refresh inline or wait for the in-flight refresh.
Source: code-review, spec review · claude-opus-5-5
Generated by Claude Code
There was a problem hiding this comment.
Confirmed, and not changed: this needs a decision from Dan.
At line 534 a call whose token still works returns that token whenever a driver is attached, however few seconds the token has left. After a quiet period the plan is idle, so nothing has refreshed the token. The first call inside the 90 seconds then gets the old token, with as little as 2 seconds left.
That is the rule #1962 sets out: "The token is still valid: it gets that token, and never waits for or starts a refresh." The test a_caller_with_a_valid_token_does_not_wait_for_its_refresh (auto_refresh/tests/background.rs:130) pins it, with a token 60 seconds from expiry on an idle plan. Refreshing inline when the plan was idle, as proposed here, fails that test.
The options:
- Keep the rule as it is.
- Refresh inline when this call found the plan idle, as proposed. The first call after a quiet period waits for the refresh again, as it did before this PR.
- Refresh inline only when the token has less than a set time left, such as 10 or 30 seconds. A refresh already running or backing off still wins. The 60-second test still passes. This option also covers the current-thread runtime in the thread at line 620.
Waiting for Dan to choose.
There was a problem hiding this comment.
Done in f6e1953, as Dan decided: a refresh floor.
- A call whose token has less than the floor left refreshes it, or waits for the refresh already running. The floor is 30 seconds by default (
REFRESH_FLOOR_SECS). Above the floor, nothing changes from the stack-auth: refresh a token in the background before it expires, with backoff after a failure #1962 rule: the call gets its token at once. - Set it with
refresh_floor(Duration)onAccessKeyStrategyBuilderorDeviceSessionStrategyBuilder, orauth.WithRefreshFloorin Go. It is whole seconds, rounded up. Zero turns it off, and a floor longer than the 90-second window acts as the window. A negative floor in Go isErrConfig. - The floor applies only while a driver is attached. OIDC federation is unchanged: it refreshes on calls inside the 90 seconds before expiry.
Tests (auto_refresh/tests/background.rs):
a_call_under_the_floor_after_a_quiet_period_refreshes: the 2-second case. It gotissued-1, the old token, with the floor turned off.a_call_under_the_floor_waits_for_the_refresh_in_flight.a_configured_floor_is_honoured,a_zero_floor_never_makes_a_call_wait,a_floor_out_of_range_is_bounded, and a builder test for each strategy.a_60_second_token_is_refreshed_about_once_every_30_seconds.the_floor_does_not_change_an_engine_refreshed_by_calls.a_caller_with_a_valid_token_does_not_wait_for_its_refresh(60 seconds left) still passes.
| } | ||
| } | ||
|
|
||
| fn to_error(&self) -> crate::AuthError { |
There was a problem hiding this comment.
major Only Server keeps its kind; every other error is rebuilt through from_error_code with an empty payload, so Request, Internal and Store come back as Custom (code CUSTOM) and WorkspaceMismatch turns retryable. This PR newly hands that rebuilt error to get_token during backoff (:539) and to refresh_now (:581, the normal host-driven case). Carry the original kind (or its payload) as Server already does, and have refresh_now return this attempt's error rather than re-reading last_refresh_error.
Source: rust-security agent, verification · claude-opus-5-5
Generated by Claude Code
There was a problem hiding this comment.
Fixed in 242d872.
- A failed refresh's error is now kept and replayed as the same error.
AuthError::replay(error.rs) rebuilds every variant with the same codes, message, help, and fields.- A transport error's causes come back as their text.
- An I/O error keeps its kind and OS error code.
- A profile file's JSON error keeps its kind of error, but not its position. Its text is never copied.
refresh_nownow returns its own attempt's error. A failed refresh returns aFailedwith its error, and the cached token when the caller may keep using it. Nothing readslast_refresh_errorback.
Tests:
a_replayed_refresh_error_keeps_its_kindandrefresh_now_reports_its_own_error(auto_refresh/tests/background.rs) failed first:CUSTOMwhereREQUEST_ERRORwas expected.a_replayed_error_reads_as_the_original(error.rs) compares every variant with its replay: codes, message, help, fields, the three classifications, and the causes.
There was a problem hiding this comment.
Follow-up in ea1f057: a local mutation run of the changed lines found one mutant that no test caught. A failed refresh hands back the cached token only while now < expires_at, and nothing tested the exact second of expiry. The new test a_refresh_that_fails_as_the_token_expires_reports_its_error catches < changed to <=.
| } | ||
| } | ||
|
|
||
| fn to_error(&self) -> AuthError { |
There was a problem hiding this comment.
major Same lossy round trip as stack-auth's LastRefreshError, copied: a replayed transport failure maps to STATUS_AUTH_OTHER instead of STATUS_AUTH_TRANSPORT (and Store/InvalidToken lose their PROFILE_*/CONFIG status), so errors.Is(err, auth.ErrTransport) stops matching on the next Token during backoff. Use one lossless type from stack-auth instead of this copy, or store the original status_for_auth value at failure time and replay it.
Source: rust-security agent, code-review, standards review · claude-opus-5-5
Generated by Claude Code
There was a problem hiding this comment.
Fixed in d147e11.
The device plan now keeps the refresh's AuthError itself. A replay goes through fail_auth. That function only borrows the error, so the status and detail are the ones the failure first reported. LastFailure is gone. The access-key path goes through stack-auth's replay, from the fix in the thread on LastRefreshError.
Test: TestADeviceSessionsReplayedRefreshErrorKeepsItsKind (background_test.go) failed first with "call 1: … Request to the auth server failed, want ErrTransport".
| // Attached before the task runs, so a call right after this one | ||
| // already leaves the refresh to it. A runtime that drops the task | ||
| // unrun drops the attachment too, and the next call starts another. | ||
| let attachment = TaskAttachment(Attachment::new(control)); |
There was a problem hiding this comment.
major The task counts as a driver from spawn, before it ever runs. On a current_thread runtime kept alive and driven only by rt.block_on(strategy.get_token()), the task is never polled while tokens are usable, so calls at 10 s and 1 s left get the old token and the first call after expiry blocks on a full exchange (reproduced). The fix for the leeway comment at :534 also covers this; alternatively don't spawn on RuntimeFlavor::CurrentThread.
Source: code-review, verification · claude-opus-5-5
Generated by Claude Code
There was a problem hiding this comment.
Confirmed by reading the code, and not changed: the fix depends on the decision in the thread at line 534.
block_on on a current-thread runtime polls spawned tasks only while the future it drives is pending. A get_token with a working token is ready at once, so the background task never runs, and calls near expiry get the old token.
Two fixes do not work:
- Not spawning on a current-thread runtime.
#[tokio::test]and#[tokio::main(flavor = "current_thread")]are current-thread runtimes. They do run the task whenever they wait on anything else. Every background test runs on one. - Counting the task as a driver only once it first runs. The first call would then refresh inline, and
a_caller_with_a_valid_token_does_not_wait_for_its_refreshfails.
Option 3 in the thread at line 534 covers this case: a call refreshes inline when its token has less than a set time left. Waiting for Dan to choose.
There was a problem hiding this comment.
Done in f6e1953: the refresh floor from the thread at line 534 covers this case.
On a current-thread runtime that never runs the background task, a call with less than 30 seconds left now refreshes the token itself. a_block_on_caller_gets_a_fresh_token_under_the_floor drives a strategy only with block_on(get_token()).
- At 60 seconds left, the call gets the cached token, and the task never ran.
- At 10 seconds left, the call gets a fresh token.
With the floor turned off, that test fails: the call got the old token.
| let token = load_device_token(workspace_dir, base_url)?; | ||
| let next = { | ||
| let mut plan = plan.borrow_mut(); | ||
| plan.schedule.observe(&token, now_secs()); |
There was a problem hiding this comment.
minor When auth.json's token has no refresh token, cannot_refresh lands on the throwaway session's schedule, not this DevicePlan, so refresh_at stays past and every Token makes the Go loop take the auth.json flock and run a no-op refresh (at most once a second) until expiry. After observe here and in next_refresh, call plan.schedule.cannot_refresh() when token.refresh_token().is_none().
Source: code-review, spec review · claude-opus-5-5
Generated by Claude Code
There was a problem hiding this comment.
Fixed in d147e11.
DevicePlan::observe now marks the plan with cannot_refresh when the token in auth.json has no refresh token. It is used everywhere the plan reads the token: Token, next_refresh, refresh_ahead, and after a refresh.
Test: TestADeviceSessionWithNoRefreshTokenIsNeverDueARefresh (background_test.go) failed first: a refresh was due for a token with no refresh token.
| /// | ||
| /// A native strategy refreshes ahead from a Tokio task of its own, and | ||
| /// needs no driver. | ||
| pub fn drive_refresh(&self) -> RefreshDriver { |
There was a problem hiding this comment.
minor drive_refresh and next_refresh have no caller outside this file's tests (the guest keeps its own DevicePlan and calls only refresh_now), yet they and RefreshSchedule (new, cannot_refresh, REFRESH_AHEAD_SECS, REFRESH_JITTER_SECS unused outside the crate) become crates.io semver surface. Drop the two methods and narrow or #[doc(hidden)] the schedule API.
Source: standards review · claude-opus-5-5
Generated by Claude Code
There was a problem hiding this comment.
Not changed: the public API is a decision for Dan.
The PR description lists this API as deliberate. RefreshSchedule is public. Both strategies have drive_refresh, next_refresh, and refresh_now for a WebAssembly host. It is true that nothing outside the tests calls DeviceSessionStrategy::drive_refresh or next_refresh today. The Go guest rebuilds its device session for each refresh, so it keeps a plan of its own.
The guest is a separate crate, so RefreshSchedule has to stay public. The guest uses observe, used, attempt_started, refresh_failed, backing_off, next, and cannot_refresh.
The options:
- Keep the API as it is, for a future host.
- Drop the two device-session methods, and keep the schedule as it is.
- Also hide
RefreshSchedule::newand the three constants from the documentation.
Waiting for Dan to choose.
There was a problem hiding this comment.
Done in d94fbd9, as Dan decided: DeviceSessionStrategy::drive_refresh and next_refresh are gone, with their two tests.
DeviceSessionStrategy::refresh_now stays, because the Go guest calls it. RefreshSchedule and its constants stay public. AccessKeyStrategy keeps its drive_refresh, next_refresh, and refresh_now. The PR description now says so.
| _ = refresh(ctx) | ||
| return | ||
| } | ||
| if !s.refreshing.TryLock() { |
There was a problem hiding this comment.
minor LockPath("auth.json") → withRefreshLock → withRefresh(ctx) duplicates strategy.go:~412-431, so the lock order can drift between the two. Extract a helper taking the guest call, after each caller has taken refreshing its own way.
Source: standards review · claude-opus-5-5
Generated by Claude Code
There was a problem hiding this comment.
Fixed in d66a3f6.
Strategy.refreshDeviceSession (strategy.go) now has the three steps: it gets the auth.json lock path, takes the lock for the refresh, and marks the refresh context. token and refreshAhead both call it, after each takes refreshing its own way. Nothing else changed. The Go auth tests pass, with -race too.
While a failed refresh backs off, the engine hands its error to every caller whose token has expired, and to refresh_now. The engine kept only the error's code and message, so every error but a server fault came back as AuthError::Custom. A transport failure lost REQUEST_ERROR, and a workspace mismatch became retryable. AuthError::replay rebuilds an error of the same variant, with the same codes, message, help, and fields. A transport error's causes come back as their text. An I/O error keeps its kind and OS error code. A profile file's JSON error keeps its kind of error, but not its position, and its text is never copied. refresh_now now returns its own attempt's error. A failed refresh returns its error, with the cached token when the caller may keep using it, so nothing reads the shared last error back.
…state The guest kept a failed device session refresh's error as a code and message. A transport failure replayed during the backoff came back as STATUS_AUTH_OTHER, and errors.Is(err, auth.ErrTransport) stopped matching. The plan now keeps the AuthError itself, and replays it through fail_auth, so the status and detail are the ones the failure first reported. A token in auth.json with no refresh token cannot be refreshed, but the guest's plan still made a refresh due for it. The refresh loop then took the auth.json lock for a refresh that did nothing, once a second while the token was in use. The plan now marks such a token as one it cannot refresh, wherever it reads the token.
Token and the refresh loop each took the auth.json lock path, held the lock and marked the refresh context in the same three steps. Both now call Strategy.refreshDeviceSession, so the order of those steps cannot drift between them.
…ts error A failed refresh hands the caller the cached token only while that token is still usable. The mutation gate found no test for the exact second of expiry. A token that expires as the refresh fails must give the caller the refresh's error.
The CRAP gate failed on AuthError::replay: one match with a branch for every variant had a complexity of 35. That is above the threshold of 30 even with every line covered. The variants with a fixed message, and Custom, now replay through their code and message. The CRN error, the access key error and a profile file's JSON error each have a small function of their own. The result of a replay is unchanged. The replay test now builds each region error, CRN error, and access key error, and a JSON read failure, so every branch runs. Locally the largest score among these functions is 19.1.
…next_refresh Nothing outside the tests called them. The Go guest rebuilds its device session for each refresh, so it keeps a refresh plan of its own and calls only refresh_now. Dropping them keeps them out of the published API. RefreshSchedule, and AccessKeyStrategy's three host calls, stay.
With a background task or a host refreshing ahead, a call never refreshed a token that still worked. After a quiet period, or on a current-thread runtime that never ran the task, a call could get back a token with 2 seconds left. Now a call whose token has less than the refresh floor left refreshes it, or waits for the refresh already running. The floor is 30 seconds unless set with refresh_floor on AccessKeyStrategyBuilder or DeviceSessionStrategyBuilder, and auth.WithRefreshFloor in Go. Zero turns it off, and a floor longer than the 90-second window acts as the window. Above the floor, a call still gets its token at once. The floor applies only while a driver is attached. An OIDC engine is refreshed by its calls. It works as before. A 60-second token is inside the 90-second window from the start. Its background refresh is due half way through its life, which is the default floor. It is exchanged about once every 30 seconds while in use.
Four mutants of the floor check in get_token timed out in the mutation gate instead of failing. Under each, two tests waited forever for a refresh that the mutant never started, and the gate counts a timeout as a failure. Those waits now end after a second of virtual time. A new test checks the floor's boundary. A token with exactly the floor left is handed out at once. One with a second less is refreshed.
Run on the PR's whole diff, five mutants of RefreshSchedule timed out locally rather than failing. With backing_off always true, the backoff-retry tests waited forever for it to end, and the multi-thread soak ran past the gate's limit. With the jitter generator broken, a subtraction overflowed inside a refresh and left a caller waiting. wait_out_backoff now fails after 5 seconds, and the multi-thread soak after 30. The jitter subtraction saturates, as the rest of the plan's arithmetic does. A new test checks that the jitter stays below its limit and reaches every value under it.
The background refresh of a token is due 90 to 120 seconds before it expires, both ends included. The jitter is 0 to 30 seconds, and the plan's own window test pins both ends. The background test instead asserted that the refresh ran strictly before the 90-second leeway. With a jitter of 30 it ran at the leeway's start, so the test failed about one run in 31. The plan's documented rule is kept: the refresh is due when the leeway starts, at the latest. The test now seeds the plan for each end of the window. It checks that the refresh runs at exactly that time, so its result no longer depends on chance.
Next caps the expiry of each refreshed token at 30 days. It also treats a token that it loads from a store as expired when the token claims more than 30 days. This branch plans each refresh from the expiry of the cached token. - install_refreshed_token caps the new token first, and then plans the next refresh from the capped expiry. So the plan and the cache use the same expiry. - refresh_now is new on this branch. It loads a token from the store when none is cached. That load now goes through distrust_overlong, as the load in get_token does.
Builds on #1965, now merged into
next. The branch sits on #1965's last commit (9b6f4b00c), so this PR shows only its own five commits.Summary
An SDK gets the access token it shows ZeroKMS (the key service) from CTS (the CipherStash Token Service), through the
stack-authRust crate. A token lasts about 15 minutes. Until now nothing refreshed a token before a call needed it. The first call in the last 90 seconds started the refresh and waited for it, a new connection to CTS and sometimes about a second. After a failure, every later call started another refresh at once.Now the token is refreshed in the background, before it expires, and no call waits for CTS while its token has more than 30 seconds left. After a failed refresh the next attempt backs off, and calls stop asking CTS themselves. The rule lives once, in
stack-auth. Nativelystack-authruns it on a Tokio task, which covers Rust and@cipherstash/authon Node. The Go SDK runs it from a goroutine per strategy.What a call does now
stack-authalready stops asking for a minute.The refresh runs only while the strategy is in use. Each refresh attempt clears a "used" mark that every call sets, so a process that stops asking for tokens stops asking CTS too.
Changes
stack-auth
RefreshSchedule(new, public): the rule, as plain data. It decides when a token's refresh is due, the backoff after a failure, and the idle rule. It reads no clock and starts no task. Property-tested with proptest.AutoRefresh) keeps aRefreshSchedule.get_token. The task holds the strategy through aWeak, so dropping the strategy ends it.OidcFederationStrategystarts no task. Its per-JWT engines are builtrefreshed_by_calls(), so each user's token is still refreshed by that user's calls in the last 90 seconds, as before.REFRESH_FLOOR_SECS), set withrefresh_floor(Duration)onAccessKeyStrategyBuilderandDeviceSessionStrategyBuilder. It is whole seconds, rounded up. Zero turns it off, and a floor longer than the 90-second window acts as the window. It does not apply to OIDC federation, which refreshes on calls inside the 90 seconds before expiry.AccessKeyStrategy::drive_refresh()returns aRefreshDriverguard. While it lives, calls leave refreshing ahead to the host, down to the refresh floor.AccessKeyStrategy::next_refresh()andrefresh_now()are the two calls the host's timer makes.DeviceSessionStrategyhas onlyrefresh_now(): the Go guest rebuilds its device session for each refresh and keeps its own plan.AuthError::replay): the same variant, codes, message, help, and fields.refresh_nowreturns its own attempt's error.Go SDK
sa_auth_next_refreshandsa_auth_refresh_ahead.refresh_aheadflag in the strategy config. Go sets it for access keys and device sessions, and the guest then holds aRefreshDriver.RefreshSchedule(only the plan, never the token) and replays the last refresh error while it backs off. A token under the floor is reported as needing a refresh, so every caller waits for it.refresh_floor_secsfield in the access-key and device-session config.auth.Strategy(access key and device session) runs a refresh loop goroutine (auth/background.go).Token. It asks the guest when the next refresh is due, sleeps, then refreshes through the step loop.Tokendoes.weak.Pointer, and never holds the profile's lock while it sleeps.Strategy.Closestops it and waits for it.ProfileStore.Closeends it. A strategy the application forgets to close is still collected, and its cleanup ends the loop.auth.WithRefreshFloor(time.Duration)sets the refresh floor of an access-key or device-session strategy. A negative floor isErrConfig.Docs
languages/golang/CHANGELOG.md(Unreleased, Changed).auth/doc.goandauth/README.md.stack-authrustdoc's "Token refresh" section.@cipherstash/authchangeset.Verification
Red first, in its own commit (
7e1751504). The tests failed on the base for the stated reasons:All of them pass on this branch.
Every check below was run on this branch on top of #1965's last commit (
9b6f4b00c). The merge into the currentnextis clean;nexthas moved on only with thestack-encryptframe refactor (#1959).stack-auth
cargo nextest run -p stack-auth --all-features: 359 tests, 357 passed. The 2 failures (device_code::tests::test_poll_for_token_invalid_client,…_invalid_grant) also fail on fix(golang): other calls no longer wait behind a token refresh #1965's head under full-suite load: 2 failures in 1 of 3 full runs there. They pass alone on both, 5 runs out of 5 here.clippy --no-deps -p stack-auth --all-targets --all-features -D warnings: clean.-D warnings: clean.cargo check --target wasm32-unknown-unknown -p stack-auth-wasm: clean.clippy -p stack-auth --target wasm32-unknown-unknownreports one error inoidc_federation_strategy.rs:734, which this PR doesn't touch. It fails the same way on fix(golang): other calls no longer wait behind a token refresh #1965's head, and CI only runscargo checkfor that target.stack-auth-nodeandstack-encrypt:cargo check --all-targetsclean.cancellation_soak_long: passes, all four seeds in both modes. Background: about 2,200 rotations and 300 to 360 injected failures per seed. Call-driven: about 6,000 rotations.--in-diffon stack-auth:ad7a73107adds the tests that catch them.Drop for AutoRefreshmutant. Its own test failed in 5 s; the run timed out because an unrelated test was slow with four builds at once. Run on its own, the mutant is caught.Go SDK
go vet: clean. golangci-lint: 0 issues.go test -race ./auth/... ./internal/...: 5 full runs of./auth, plus 8 repeats of the cancel tests and 15 of the one test below.WARNING: DATA RACE, reported duringTestAnAccessKeyExchangeEndsWithItsCallerin the first full run. The report was lost and it has not come back. See Review notes.TestDeviceSessionCallersDoNotWaitBehindARefreshOfAValidToken: under-race, opening the profile outlasted the test token's 4 seconds. Fixed in5a8df6b5d; the test then passed three times under-race.scripts/go-binding-test.sh languages/golang: exit 0, every module, includingencrypt.--tests: clean;token_stepsunderinternal/wasmtestrun: 7 passed.Related
Closes #1962
Refs #1958, #1965, #1963, #1964
Review notes
Short-lived tokens (60 seconds, such as Clerk's). On an access-key or device-session strategy, a 60-second token is inside the 90-second window from the moment it arrives. Its background refresh is due half way through its life, at 30 seconds. The default floor starts at the same point. So calls in the first 30 seconds get it at once, and calls after that refresh it or wait for the background refresh. While in use, it is exchanged about once every 30 seconds.
a_60_second_token_is_refreshed_about_once_every_30_secondspins this: one call a second for ten minutes, no token handed out with less than 30 seconds left, 19 to 22 exchanges. For short-lived tokens, keep the floor at or below half the token's lifetime. With a larger floor, calls start waiting before the background refresh is due. On OIDC federation the floor does not apply. There, every call inside the 90 seconds before expiry refreshes, as before this PR, so a 60-second CTS token is re-exchanged on each call.Existing tests changed. The tests of the engine's in-window paths (the cancellation tests, and the
auto_refreshunit and stress tests) now build their engine withrefreshed_by_calls(), the same switch the OIDC engines use. That path is still what wasm32 runs with no host driving it, so it stays covered. Three tests whose premise was "the call in the window refreshes" were rewritten for the background model:TestCallersDoNotWaitBehindARefreshOfAValidToken;TestDeviceSessionCallersDoNotWaitBehindARefreshOfAValidToken;test_stress_expiring_but_usable_non_blocking.Two tests now wait out the backoff before retrying:
a_server_fault_is_retried_after_its_backoff, and the two "restores the refresh token" tests.OIDC keeps refreshing from calls (
65fa82bec). An earlier commit gave each per-JWT engine of anOidcFederationStrategyits own background task, which re-exchanged that user's JWT for as long as the user stayed active. That would mean more calls to CTS for a server with many users, and a late re-exchange can fail once the JWT itself has expired. OIDC engines now have no task;a_users_token_is_refreshed_by_their_calls_not_a_background_taskfails (1 driver attached) without the change. The Go guest already treated OIDC as idle.Left for a follow-up: a JS host timer for the WASM build of
@cipherstash/auth. It has no background task, so a call in the last 90 seconds still refreshes and waits for it, now with the backoff. A host timer could drive it throughAccessKeyStrategy'sdrive_refresh/next_refresh/refresh_now, as the Go guest does. Not filed as an issue.A data race reported once, not reproduced. One
-racerun of./authreported a race whileTestAnAccessKeyExchangeEndsWithItsCaller(one of fix(golang): other calls no longer wait behind a token refresh #1965's cancel tests) ran. A detected race can come from goroutines an earlier test left behind. The report was filtered out of the log before anyone read it. It did not come back in 4 more full runs, 8 repeats of the cancel tests, or 15 repeats of that test. CI's-racejob is the next place to look. It may be in this PR's loop or in fix(golang): other calls no longer wait behind a token refresh #1965's step loop.No hand-written Rust changelog.
packages/stack-auth/CHANGELOG.mdis written by release-plz from the commits, so this PR does not edit it.